<?php
namespace Common\Model;

class InvestModel extends \Think\Model
{
	//自动验证
	protected $_validate = array(
			//新增
			array('user_id', '/^[1-9]\d*$/', '请传入用户ID', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),



	);
	
	//自动完成
	protected $_auto = array(
			array('create_time', NOW_TIME, self::MODEL_INSERT, 'string'),
			array('update_time', NOW_TIME, self::MODEL_BOTH, 'string'),

	);
	
	/**
	 * 添加定单
	 * @param array $data
	 * @param int $userId 用户id
	 * @param number $type 冻结类型，0-用户下单，1-系统下单
	 */
	public function addOrder(array $data, $userId, $type = 0)
	{
		//查询用户认证信息
		$user = M('User')->where(array('id' => $userId))->field('id,mobile,bit_status')->find();
		if(!$user) return array('error' => 1, 'info' => '用户信息查询失败');
		
		//查询账户信息
		$account = M('Account')->where(array('user_id' => $userId, 'status' => 1))->find();
		if(!$account) return array('error' => 1, 'info' => '账户信息查询失败');
		

		//D('UserDetail')->updateRealname($real, $userId);
		if($data['paysuccess']){
			$this->paysuccess = $data['paysuccess'];
		}

		//合格认证
		//if(!($user['bit_status'] & 128)) return array('error' => 3, 'info' => '您没有通过合格认证');
		
		//创建数据对象
		if(!$this->create($data)) return array('error' => 1, 'info' => $this->getError());
		
		//获取基金信息
		$good_info = $this->good_info;
		foreach($good_info as $key=>$val){
			$good_id = $val[0];
			$gooddata = M('good')->where(array('id' => $this->$good_id))->find();
			if(!$gooddata) return array('error' => 1, 'info' => '基金信息查询失败');
		}
		//在支付成功时更新
		$this->end_time = 0;
		$this->effective_time = 0;
		
		//购买份数限制
		//if($fund['min_count'] > 0 && $this->count < $fund['min_count'])  return array('error' => 1, 'info' => "最少购买份数为{$fund['min_count']}份");
		//if($fund['max_count'] > 0 && $this->count > $fund['max_count'])  return array('error' => 1, 'info' => "最大购买份数为{$fund['maxn_count']}份");
		
		//TODO：如果有购买金额限制
		//
		$amount = $this->amount;
		//获取合同信息

		//生成定单号
		$orderNo = $this->order_no = date('YmdHis', NOW_TIME) . \Common\Util\Util::randStr(6);
		
		//开启事务
		$this->startTrans();
		
		try {


			$id = $this->add();

			if(!$id) throw new \Exception('定单提交失败');
			//提交事务
			$this->commit();
			$return = array('error' => 0, 'info' => array("id"=>$id,"order_no"=>$orderNo));
		} catch (\Exception $e) {
			//回滚事务
			$this->rollback();
			$return = array('error' => 1, 'info' => $e->getMessage());
		}
		
		return $return;
	}
	
	/**
	 * 订单自动更新
	 */
	public function autoUpdate()
	{
		//查询计息结束的订单
		$where['failure_time'] = array('lt', NOW_TIME);
		$where['status'] = 3;
		$investList = $this->where($where)->select();
		if($investList === false) return array('error' => 1, 'info' => '订单查询失败');
		
		$count = 0;
		//存在就处理
		if($investList) {
			foreach ($investList as $invest) {
				$this->startTrans();
				try {
					$res = $this->incomeInternal($invest);
					if($res['error'] === 1)	throw new \Exception($res['info']);
					$res = $this->where(array('id' => $invest['id']))->save(array('status' => 1));
					if(!$res)	throw new \Exception('更新成功');
				} catch (\Exception $e) {
					
				}
			}
		}
	}
	
	private function incomeInternal($invest)
	{
		//查询最后一天计息的净值
		$endDate = date('Y-m-d', strtotime('-1 day', $invest['end_time']));
		$endNetvalue = D('FundNetvalue')->netvalueByDate($endDate);
		if($previous['error'] === 1) return array('error' => 1, 'info' => '最后一天计息净值查询失败');
		$endNetvalue = $endNetvalue['info'];
		
		//查询计息开始时间的净值
		$investNetvalue = M('FundNetvalue')->find($invest['netvalue_id']);
		if(!$investNetvalue) return array('error' => 1, 'info' => '第一天计息净值查询失败');
		
		//查询该订单赎回记录
		$redeem = M('Redeem')->where(array('status' => 1, 'invest_id' => $invest['id']))->select();
		if($redeem === false) return array('error' => 1, 'info' => '第一天计息净值查询失败');
		
		//计算本金
		$capital = $invest['amount'];
		if($redeem) {//减去已赎回的本金
			$reAmount = 0;
			foreach($redeem as $re) {
				$reAmount = bcadd($reAmount, bcmul($re['count'], $invest['unit_price'], 4), 4);
			}
			$capital = bcsub($capital, $reAmount, 4);
		}
		
		//计算收益
		$rate = bcdiv(bcsub($endNetvalue['value'], $investNetvalue['value'], 4), $investNetvalue['value'], 4);
		$income = bcmul($invest['amount'], $rate, 4);
		
		//总金额
		$total = bcadd($capital, $income, 2);
		
		//保存账户信息
		$data['amount'] = $total;
		$data['investIncome'] = $income;
		$data['target_id'] = $invest['id'];
		$res = D('Account')->updateAcc($data, $invest['user_id']);
		return $res;
	}
	
	/**
	 * 异步通知处理订单
	 * TODO:连连支付已不用，该功能需根据第三方支付进行修改
	 */
	public function notify()
	{
		$param = file_get_contents('php://input');
		$param = json_decode($param, true);
		$resultPay = strtoupper($param['result_pay']);
		
		//判断订单号
		$order_no = I('data.no_order', '', '/^\d{20}$/', $param);
		if(!$order_no) return array('error' => 1, 'info' => '订单号不存在');
		
		//判断订单是否存在
		$invest = $this->where(array('order_no' => $order_no, 'status' => 2))->field('id,user_id')->find();
		if(!$invest) return array('error' => 1, 'info' => '订单可能被取消或支付完成或不存在');
		
		//判断支付是否成功
		$pay = new \Common\Util\LLPay();
		$payResult = $pay->notifyVerify($param);
		if($payResult['error'] === 1) return array('error' => 1, 'info' => $payResult['info']);
		
		//连连支付在支付时会进行实名认证，支付成功，则实名认证通过
		$user = M('User')->where(array('id' => $invest['user_id']))->field('id,mobile,bit_status')->find(); 
		$bitStatus = $user['bit_status'] | 1;
		M('User')->where(array('id' => $user['user_id']))->filed('bit_status')->save(array('bit_status' => $bitStatus));
		
		//开启事务
		$this->startTrans();
		$return = array();
		
		try {
			//查询
			$res = D('Pay')->where(array('pay_bill' => $param['oid_paybill']))->find();
			if($res) throw new \Exception('订单已支付成功');
			
			//记录异步通知结果
			$lldata['platform'] = 'llpay';
			$lldata['order_no'] = $param['no_order'];
			$lldata['pay_bill'] = $param['oid_paybill'];
			$lldata['result_pay'] = $param['result_pay'];
			$lldata['settle_date'] = $param['settle_date'] ? $param['settle_date'] : '';
			if($param['pay_type']) $lldata['pay_type'] = $param['pay_type'];
			$res = D('Pay')->addResult($lldata);
			if($res['error'] === 1) throw new \Exception($res['info']);
			
			//更新资金流水日志
			$alData['target_id'] = $invest['id'];
			$alData['type'] = 0;
			$res = D('AccountLog')->changeStatus($alData);
			if($res['error'] === 1) throw new \Exception($res['info']);
			
			//更新订单状态
			$res = $this->where(array('id' => $invest['id']))->save(array('status' => 1));
			if(!$res) throw new \Exception('订单状态更新失败');
			
			$this->commit();
		} catch (\Exception $e) {
			$this->rollback();
			record_error_log(__FILE__, __LINE__, $e->getMessage(), $user['id'], $user['mobile']);
		}
		
		return $payResult;
	}
	
	/**
	 * 查询投资记录
	 */
	public function searchInvest($where = false, $option = false, $order='', $field=true)
	{
		if($option ) {
			if($option['page'] && $option['size']) {
				$page = $option['page'];
				$size = $option['size'];
				$this->page($page, $size);
			}
		}
		$order = "create_time desc";
		if($where) $this->where($where);
		$invest = $this->order($order)->select();
		$return = array();
		foreach($invest as $key=>$val){
			$good_info = json_decode($val['good_info'],true);
			if(!is_array($good_info)){
				$good_info = json_decode($good_info,true);
			}
			$receipt_id = $val['receipt_id'];
			$receiptinfo = M("Receipt")->where(array("id"=>$receipt_id))->find();
			$val['receiptinfo'] = $receiptinfo;
			unset($val['good_info']);
			$val['amount'] = floatval($val['amount']);
			$val['status'] = intval($val['status']);
			$val['type'] = intval($val['type']);
			if($val['type'] == 1){
				$val['type_name'] = "抢购商品";
			}elseif($val['type']==2){
				$val['type_name'] = "预约商品";
			}elseif($val['type']==3){
				$val['type_name'] = "定制商品";
			}
			if($val['status'] == 1){
				$val['status_name'] = "完成";
			}elseif($val['status']==3){
				$val['status_name'] = "待发货";
			}elseif($val['status']==4){
				$val['status_name'] = "待收货";
				$expressinfo = M("Express")->where(array("invest_id"=>$val['id']))->find();
				switch($expressinfo['type']){
					case 1:
						$val['posttype'] = "顺丰";
						break;
					case 2:
						$val['posttype'] = "深通";
						break;
					case 3:
						$val['posttype'] = "圆通";
						break;
					case 4:
						$val['posttype'] = "韵达";
						break;
					case 5:
						$val['posttype'] = "大丰";
						break;
					case 6:
						$val['posttype'] = "诚信";
						break;
				}
				$val['postid'] = $expressinfo['express_code'];
			}elseif($val['status']==5){
				$val['status_name'] = "待评价";
			}elseif($val['status']==2){
				$val['status_name'] = "待付款";
			}elseif($val['status']==10){
				$val['status_name'] = "已取消";
			}
			$val['create_time'] = date("Y-m-d H:i:s",$val['create_time']);

			$return[$key]=$val;
			foreach($good_info as $k=>$v){
				if($v['sku'] == ""){
					$goodlist = M("Good")->where(array("id"=>$v['good_id']))->find();
				}else{
					$goodlist = M("Good")
						->join("left join mt_good_price on mt_good.id=mt_good_price.good_id")
						->where(array("mt_good.id"=>$v['good_id'],"mt_good_price.id"=>$v['sku']))->find();

					$card_ids = explode(",",$goodlist['category_id']);
					$where['id'] = array("in",$card_ids);
					$cateinfo = M("GoodCategory")->where($where)->select();
					$catelist = "";
					if(is_array($cateinfo)){
						foreach($cateinfo as $ks=>$vs){
							$catelist .= $vs['name'].":".$vs['value'].",";
						}
					}
					$return[$key]["goodlist"][$k]["sku"] =  substr($catelist,0,-1);
				}
				$return[$key]["goodlist"][$k]['img_path'] = "http://121.14.38.35/".explode(",",$goodlist['img_path'])[0];
				$return[$key]["goodlist"][$k]["good_name"] =  $goodlist['title'];
				$return[$key]["goodlist"][$k]["count"] =  intval($v['count']);
				$return[$key]["goodlist"][$k]["min_price"] =  floatval($v['price']);
			}
		}
		return $return;
	}
}
